<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/24 0024
 * Time: 下午 1:54
 */

namespace app\admin\model;


use think\Db;
use think\Model;

class BranchOffice extends Model
{

    public function branchOfficeInfo()
    {
        return $this->hasOne('BranchOfficeInfo','user_id','id','','LEFT');
    }

    public function city()
    {
        return $this->hasOne('City','cityID','city_id');
    }

    public function agency()
    {
        return $this->hasOne('BranchAgency','user_id','id','','LEFT');
    }

    /**
     * 市级交易等数据
     * @author: yanggang
     * @date: 2018/7/30 0030
     * @param $city_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_rank_top($city_id,$params)
    {
        if (!empty($params['start_date']) && !empty($params['end_date'])){
            $start_time = strtotime($params['start_date']);
            $end_time = strtotime($params['end_date']);
            $sql =  'select sum(s_p)/100 as spp,city_id ,c.name from
( select sum(price) as s_p,shop_id,(select city_id from dy_shop where dy_shop.shop_id = dy_tuan_order.shop_id) as city_id from dy_tuan_order  
Where pay_status = 2 and  order_type <>3 and pay_time BETWEEN '.$start_time.' AND '.$end_time.'
group by shop_id ) as aaa,dy_city as c
Where aaa.city_id = c.cityID
GROUP BY city_id ORDER BY spp desc';
        }else{
            $sql = 'select sum(s_p)/100 as spp,city_id ,c.name from
( select sum(price) as s_p,shop_id,(select city_id from dy_shop where dy_shop.shop_id = dy_tuan_order.shop_id) as city_id from dy_tuan_order  
Where pay_status = 2 and  order_type <>3 
group by shop_id ) as aaa,dy_city as c
Where aaa.city_id = c.cityID
GROUP BY city_id ORDER BY spp desc';
        }



        $all = Db::query($sql);
        if (empty($all)){
            $data = [];
            $json_data = json_encode([]);
            return compact('data','json_data','rank');
        }
        $rank = 0;
        foreach ($all as $key => $value) {
            //查询城市负责人
            $branch = BranchOffice::where('city_id', $value['city_id'])->find();

            if ($branch) {
                $arr = [];
                $arr['name'] = City::where('cityID', $value['city_id'])->value('name');
                $arr['username'] = BranchOfficeInfo::where('user_id', $branch->id)->value('realname') ?? '未知';
                $arr['spp'] = $value['spp'];
                $data[] = $arr;
            }

            if ($city_id == $value['city_id']) {
                $rank = $key + 1;
            }
        }
        $data = array_slice($data, 0, 10);
        $echart_data = ['spp' => array_column($data, 'spp'), 'name' => array_column($data, 'name')];
        $json_data = json_encode($echart_data);
        return compact('data','json_data','rank');
    }

    /**
     * 区级交易等数据
     * @author: yanggang
     * @date: 2018/7/30 0030
     * @param $city_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_rank_agency($city_id,$params)
    {
        $data = (new BranchOffice())
            ->with('agency')
            ->where([
                'city_id' => $city_id,
                'type' => 3
            ])
            ->select();
        if (empty($data)){
            $arr = [];
            $json_data = json_encode([]);
            return compact('arr','json_data');

        }
        $arr = [];
        $start_time = '';
        $end_time = '';
        if (!empty($params['start_date']) && !empty($params['end_date'])) {
            $start_time = strtotime($params['start_date']);
            $end_time = strtotime($params['end_date']);
        }
        foreach ($data as $k => $v) {
            //社区代理推荐商家数量
            if ($start_time && $end_time){
                $shop_ids = Shop::where('agency_id', $v['id'])
                    ->whereBetween('agency_time',[$start_time,$end_time])
                    ->column('shop_id');
            }else{
                $shop_ids = Shop::where('agency_id', $v['id'])->column('shop_id');
            }
            $count = count($shop_ids);
            if($count == 0){
                $amount = 0;
            }else{
                if ($start_time && $end_time) {
                    //交易额
                    $amount = (new TuanOrder())
                        ->where([
                            'pay_status' => 2,
                            'order_type' => ['<>', 3]
                        ])
                        ->whereBetween('create_time', [$start_time, $end_time])
                        ->whereIn('shop_id', $shop_ids)
                        ->sum('price');
                } else {
                    //交易额
                    $amount = (new TuanOrder())
                        ->where([
                            'pay_status'=>2,
                            'order_type'=>['<>',3]
                        ])
                        ->whereIn('shop_id',$shop_ids)
                        ->sum('price');
                }

                $amount /= 100;
            }

            $arr[$k]['number'] = $count;
            $arr[$k]['price'] = $amount;
            $arr[$k]['realname'] = $v['agency'] ? $v['agency']['realname'] : '社区代理';
            $sort[$k] = $amount;
            $sort_num[$k] = $count;
        }

        array_multisort($sort, SORT_DESC,$sort_num,SORT_DESC, $arr); //按照交易额和数量排序
        array_splice($arr,10); //只取前10
        $json_data =  json_encode(['price'=>array_column($arr,'price'),'number'=>array_column($arr,'number'),'name'=>array_column($arr,'realname')]);

        return compact('arr','json_data');
    }

    /**
     * 交易额与交易量
     * @author: yanggang
     * @date: 2018/7/31 0031
     * @param $shop_ids
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_data($shop_ids,$params)
    {

        /**默认查最近7天
         *查询日期包括当天
         */
        if (empty($params['start_date'])){
            $num = 6;
            $end_time = time();
            $start_time = strtotime('-'.$num.'day',strtotime(date('Y-m-d')));
            $start_date = date('Y-m-d',$start_time);
        }else{
            $start_date = $params['start_date'];
            $end_date = $params['end_date'];

            $start_time = strtotime($start_date);
            $end_time = strtotime($end_date);

            if($end_time > time()){ //结束时间不能大于当前时间
                $end_time = time();
            }
            $num = ceil(($end_time+1-$start_time)/3600/24) ;
            $start_date = date('Y-m-d',strtotime($start_date));
        }

        if ($num != 1){
            foreach (range(0,$num-1) as $key=>$item){
                $date_arr[] = date('Y-m-d',strtotime('+'.$item.'day',$start_time));
            }
        }else{
            $date_arr = [$start_date];
        }



        $res = (new TuanOrder())
            ->field('price,create_time ,pay_time,update_time')
            ->where([
                'pay_status'=>2,
                'order_type'=>['<>',3]
            ])
            ->whereIn('shop_id',$shop_ids)
            ->whereBetween('pay_time',[$start_time,$end_time])
            ->select();
        $res = collection($res)->toArray();

        $list = array_map(function($val){
            return [
                'price'=>$val['price'],
                'pay_time'=>date('Y-m-d',$val['pay_time']),
            ];
        },$res);

        $time_arr = array_column($list,'pay_time');
        $amount_arr = [];
        $count_arr = [];
        foreach ($date_arr as $item){
            $keys = array_keys($time_arr,$item);
            $amount = 0;
            foreach ($keys as $val){
                $amount += $list[$val]['price'];
            }

            $amount_arr[] = $amount/100 .'';
            $count_arr[] = count($keys);

        }

        return compact('amount_arr','date_arr','count_arr');
    }
}